import * as moment from 'moment';

export const handleTimes = (times: (number | string | Date | moment.Moment)[]) => {
  return times.map((item) => moment(item).hour() * 60 + moment(item).minute());
};
const reg =
  /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);
type TimeVal = React.ReactNode | Date | number | string;

export const handleTime = (time?: TimeVal, format: string = 'YYYY-MM-DD HH:mm:ss') => {
  if (!time) return '暂无数据';
  if (typeof time === 'string') return moment(time).format(format);
  if (typeof time === 'number') return moment(time).format(format);
  return moment(time?.toString()).format(format);
};

export const phoneNumberReg = /^1\d{10}$/;

export const specialCharReg =
  /[`~!@#$^&*()=|{}':;',\[\].<>《》\/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？\s]/;

export const pklotReg = /[`~!@#$^&*=|{}''\[\]<>《》?~！@#￥……&*|{}【】‘”“'。？\s]/;

// 数字、26个英文字母或下划线组成的字符串
export const passwordReg = /^\\w+$/;

export const urlReg = /^(http|https):\/\/\w+\..+$/;

// 包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间
export const passwordReg2 = /^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$/;

// 汉字
export const zhReg = new RegExp('[\\u4E00-\\u9FFF]+', 'g');

// 由数字、26个英文字母或者下划线组成的长度小于50的字符串:
export const standardReg = /^[0-9a-zA-Z_]{1,50}$/;

// 必须由字母和数字组成
export const letterAndNumberReg = /[0-9]+[a-zA-Z]+[0-9a-zA-Z]*|[a-zA-Z]+[0-9]+[0-9a-zA-Z]*/;

export const ipAddrReg =
  /((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))/;

const CTCC_ICCID_PREFIX = ['898603', '898611'];

const CUCC_ICCID_PREFIX = ['898601', '898606', '898609'];

const CMCC_ICCID_PREFIX = ['898600', '898602', '898604', '898607'];

/**
 * 根据卡号查询运营商
 * @param iccid 卡号
 */
export function getOperatorByIccid(iccid: string): string {
  const ICCID_PREFIX = CTCC_ICCID_PREFIX.concat(CUCC_ICCID_PREFIX, CMCC_ICCID_PREFIX);
  const index = ICCID_PREFIX.indexOf(iccid.slice(0, 6));
  if (index > 4) return '中国移动';
  if (index > 1) return '中国联通';
  if (index >= 0) return '中国电信';
  return '未知运营商';
}
export const parkingSpotIdReg = /^[0-9a-zA-Z_-]{1,50}$/;

const toFixedFix = (n: number, prec: number) => {
  const temp = Math.pow(10, prec);
  return '' + Math.ceil(n * temp) / temp;
};
/**
 * 格式化数字
 * @param num 需要处理的数字
 * @param decimal 精度,默认为 '2'
 * @param dp 小数点符号,默认 '.'
 * @param th_sep 千分位符号,默认 ','
 */
export function numFormat(num: number, decimal = 2, dp = '.', th_sep = ',') {
  const _num = Number((num + '').replace(/[^0-9+-Ee.]/g, ''));
  const n = !isFinite(_num) ? 0 : _num;
  const prec = !isFinite(decimal) ? 0 : Math.abs(decimal);
  const s = (prec ? toFixedFix(n, prec) : String(Math.round(n))).split('.');
  const re = /(-?\d+)(\d{3})/;
  while (re.test(s[0])) s[0] = s[0].replace(re, '$1' + th_sep + '$2');
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dp);
}
export function leftPad(num: number | string, len: number, padding = '0') {
  return (Array(len).join(padding) + num).slice(-len);
}
type TimeType = Date | number | string;
export function diffTimes(time1: TimeType, time2?: TimeType) {
  if (!time2) return '-';
  const t1 = new Date(time1).valueOf();
  const t2 = new Date(time2).valueOf();
  // const diff = Math.ceil(Math.abs(t1 - t2) / (60 * 1000));
  const secDiff = Math.ceil(Math.abs(t1 - t2) / 1000);
  // return formatMinToHourMin(diff);
  return formatMinToHourMinSec(secDiff);
}
export const timeRender = (time?: TimeType) =>
  time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : '';

export function formatMinToHourMinSec(sec: number) {
  const h = Math.floor(sec / 3600) > 0 ? Math.floor(sec / 3600) : 0;
  const m = Math.floor((sec % 3600) / 60);
  const s = sec % 60;
  const day = Math.floor(h / 24);
  if (day > 0)
    return `${day} 天 ${leftPad(h % 24, 2)} 小时 ${leftPad(m, 2)} 分钟 ${leftPad(s, 2)} 秒`;
  return h
    ? `${h} 小时 ${leftPad(m, 2)} 分钟 ${leftPad(s, 2)} 秒`
    : `${m} 分钟 ${leftPad(s, 2)} 秒`;
}

export function formatMinToHourMin(min: number) {
  const h = Math.floor(min / 60) > 0 ? Math.floor(min / 60) : 0;
  const m = min % 60;
  return h ? `${h} 小时 ${leftPad(m, 2)} 分钟` : `${m} 分钟`;
}

export const isHttps = document.location.protocol === 'https:';

export const handleInOutType = (val?: InOutType) => {
  switch (val) {
    case 'sensor':
      return ' 地磁设备 ';
    case 'patrol':
      return ' 巡检设备 ';
    case 'manual':
      return ' 人工确认 ';
    default:
      return ' 未知来源 ';
  }
};
